package com.cug.nageoffer.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cug.nageoffer.model.entity.UserChatRecord;
import com.cug.nageoffer.model.vo.Result;
import com.cug.nageoffer.model.vo.ResultCodeEnum;
import com.cug.nageoffer.user.mapper.UserChatRecordMapper;
import com.cug.nageoffer.user.service.UserChatRecordService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserChatRecordServiceImpl extends ServiceImpl<UserChatRecordMapper, UserChatRecord> implements UserChatRecordService {

    @Override
    public void record(UserChatRecord requestParam) {
        // TODO 需判断接收信息的用户类型，将记录存储到不同的数据库中
        if(requestParam.getCategory().equals(0)){
            requestParam.setDelFlag(0);
            requestParam.setStatus(1);
            save(requestParam);
        }
        else {

        }
    }

    @Override
    public void receive(UserChatRecord requestParam) {
        // TODO 需判断接收信息的用户类型，将记录存储到不同的数据库中
        if(requestParam.getCategory().equals(0)){
            requestParam.setDelFlag(0);
            requestParam.setStatus(1);
            save(requestParam);
        }
        else {

        }
    }

    @Override
    public Result<List<UserChatRecord>> queryRecord(UserChatRecord requestParam) {
        update().eq("sender_id",requestParam.getSenderId())
                .eq("receiver_id", requestParam.getReceiverId())
                .eq("category", requestParam.getCategory())
                .eq("del_flag",0)
                .eq("status",1).set("status",2).update();
        List<UserChatRecord> recordList = query().eq("sender_id", requestParam.getSenderId())
                .eq("receiver_id", requestParam.getReceiverId())
                .eq("category", requestParam.getCategory())
                .eq("del_flag",0).list();
        List<UserChatRecord> records = new ArrayList<>();
        if(!recordList.isEmpty()){
            for (UserChatRecord record : recordList) {
                if(record.getTimestamp().after(requestParam.getTimestamp())){
                    records.add(record);
                }
            }
        }
        return Result.build(records, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<String> delete(List<Integer> ids) {
        update().in("id",ids).set("del_flag",1);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result<Long> unreadCount(UserChatRecord requestParam) {
        Long count = query().eq("sender_id", requestParam.getSenderId())
                .eq("receiver_id", requestParam.getReceiverId())
                .eq("category", requestParam.getCategory())
                .eq("del_flag", 0)
                .eq("status", 1).count();
        return Result.build(count, ResultCodeEnum.SUCCESS);
    }
}
